from iClouds.allSerializers import *
from iClouds.wechatcfg import wxChatRequest  # ,wxConf,
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from django.views import View

# from django.views.decorators.csrf import csrf_exempt, csrf_protect
# from django.utils.decorators import method_decorator
from urllib.parse import urlencode
from .Serializers import *
from .tasks import *
import logging
import hashlib
import json

logger = logging.getLogger(__name__)


# Create your views here.


def wrapper(func):
    def inner(*args, **kwargs):
        res = func(*args, **kwargs)
        return res

    return inner


class wxCallback(View):
    """微信公众号扫码登陆回调"""

    def get(self, request):
        print("Index: GET 方法")
        args = request.GET
        print(args.get("code"), args.get("state"))
        logger.info(f"[WeCallback] [GET] {request}")

        # 异步请求登录token
        if args.get("code"):
            task = wxHasLoginToken.delay(args.get("code"), args.get("state"))
        return HttpResponse("GET 方法")

    def post(self, request):
        print("Index: Post 方法")
        logger.info(f"[WeCallback] [POST] {request}")
        return HttpResponse("POST 方法")


class wxEventAlert(View):
    """微信公众号消息通知"""

    def get(self, request):
        """验证消息"""
        signature = request.GET.get("signature")
        echostr = request.GET.get("echostr")
        timestamp = request.GET.get("timestamp")
        nonce = request.GET.get("nonce")
        token = "EgNLWhG30jP9XTdArA07y47Pqa9ewCyR"
        list = [token, timestamp, nonce]
        list.sort()
        x = "".join(list)
        hashcode = hashlib.sha1(x.encode("utf8")).hexdigest()
        logger.info(f"[微信公众号消息通知] [GET] {signature} {hashcode}")

        if hashcode == signature:
            return HttpResponse(echostr)
        else:
            return HttpResponse("err")

    def post(self, request):
        print("Index: Post 方法")
        logger.info(f"[微信公众号消息通知] [POST] 收到消息推送!")
        body = request.body.decode("utf-8")
        res = paresAlert.delay(
            body,
        )
        return HttpResponse("success")


class wxPayAlert(View):
    """微信支付回调"""

    def get(self, request):
        print("Index: GET 方法")
        logger.info(f"[微信支付回调] [GET] {request}")
        return HttpResponse("GET 方法")

    def post(self, request):
        print("Index: Post 方法")
        logger.info(f"[微信支付回调] [POST] {request}")
        # logger.info(f'[微信支付回调] [POST] {request.POST.get("event_type")}')
        # body = request.body.decode("utf-8")
        body = request.POST
        res = paresWxPayCrypto.delay(
            body,
        )
        return HttpResponse("success")


class wxTextback(View):
    """测试回调"""

    def get(self, request):
        print("Index: GET 方法")
        args = request.GET
        logger.info(f"[测试回调] [GET] {args}")
        return HttpResponse("GET 方法")

    def post(self, request):
        print("Index: Post 方法")
        args = request.POST
        logger.info(f"[测试回调] [POST] {args}")
        return HttpResponse("POST 方法")


# =============================================================
class myTestViewSet(viewsets.ModelViewSet):
    __title__ = "测试接口"
    __group__ = "公用接口"
    __info__ = {"post": "测试接口"}
    __doc__ = """
    create:
    <h4>测试接口</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        # code = """
        # <xml><ToUserName><![CDATA[gh_8f0c90b10f8c]]></ToUserName>
        # <FromUserName><![CDATA[oTp3w6tt8LoQHY3x_fT560Pxm9jA]]></FromUserName>
        # <CreateTime>1717732046</CreateTime>
        # <MsgType><![CDATA[event]]></MsgType>
        # <Event><![CDATA[SCAN]]></Event>
        # <EventKey><![CDATA[441388]]></EventKey>
        # <Ticket><![CDATA[gQF28DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyZU0wT0JZZXRmTUcxclIzeWhDMVcAAgTJgmJmAwQsAQAA]]></Ticket>
        # </xml>
        # """
        # r = toDict(code)
        # print(type(r), r)
        # """
        # {
        #     'ToUserName': 'gh_8f0c90b10f8c',
        #     'FromUserName': 'oTp3w6tt8LoQHY3x_fT560Pxm9jA',
        #     'CreateTime': '1717732046',
        #     'MsgType': 'event',
        #     'Event': 'SCAN',
        #     'EventKey': '441388',
        #     'Ticket': 'gQF28DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyZU0wT0JZZXRmTUcxclIzeWhDMVcAAgTJgmJmAwQsAQAA'
        # }
        # """
        # k = paresAlert(r)
        # print(k)

        # ------------------------------------------------------

        # body = {
        #     "id": "c4454d82-1467-5fae-b0f0-6213be9a81a1",
        #     "create_time": "2024-06-08T03:05:35+08:00",
        #     "resource_type": "encrypt-resource",
        #     "event_type": "TRANSACTION.SUCCESS",
        #     "summary": "支付成功",
        #     "resource": {
        #         "original_type": "transaction",
        #         "algorithm": "AEAD_AES_256_GCM",
        #         "ciphertext": "tqJcYiofPNbIp6r+BEKraH5qybIT7XS4khLqsf6CMV0uAH7G6sfc6S9tuFDuRmNc0MnvhaZ3FHn9OyDrkp41VCog/V9p3Q7WGfoNj7nbEfXl3HnuyRdscrgJrusOAGxmfr3mVI3rR63jTQgQ1iFXi0DAiM7EcY2nZRnJqO5PRxchGv7G9MGhc8bcl0JgmXyo2HtAiAlIDBgl8i2jaI9DRTUX/zJDEVosTceoos1SmA/lGrr+1zVGM5ljFK89cMy6zCzOCeUwn3znJzkql73jKrg6KjTkiAsuupjOYMLsTG+BDVDTWFVC+/Nvy2n2OF1AwUIP9PV64a4F9HBcbL+8NFaUqn4o/qoGHcxdYKydqJ8uFW8JE/ywxV4oceFuHZJ6wMBoo1XFutrrljUPuZzuvmUUwjDIW1KueNzl9qrMSV/5Q8NkccoPD0VeVSvim7br+prteRO0b0Y+eYxyTVo7ndIVhk+Hi0fZMiswIBoJ6KT8nyJYHykwXRF0Yjxza+Bekvo5NPue/t9TGdpYpFbwQfrAY20fBeANUsxpVcDW9gRUQNCE46OCYXzt1q0UKbzzzDHwRwMGjmKMGFdNmPu2",
        #         "associated_data": "transaction",
        #         "nonce": "2sMRhK2wsDEe",
        #     },
        # }
        # res = paresWxPayCrypto.delay(
        #     body,
        # )

        # -----------------------------------------------------

        # sql = "select * from yl_wx_orders where out_trade_no=%s;"
        # db = [
        #     "MyFgGlZPsgdsYJQ8kC0ycHHCOsxsVyC6",
        # ]
        # res = PHPselectMdb(sql, 2, db)

        # -----------------------------------------------------
        # 添加计划任务
        from mysqldb.models import (
            DjangoCeleryBeatCrontabschedule,
            DjangoCeleryBeatPeriodictask,
        )
        from rest_framework import status

        task_name = request.data.get("task_name")
        cron_value = request.data.get("task_cron")
        cron_list = str(cron_value).split(" ")

        task_name = "task_name"
        task_time = timezone.now() + timedelta(
            # days=50,  # 天
            seconds=27,  # 秒
            # microseconds=10,    # 微秒
            # milliseconds=29000, # 毫秒
            # minutes=5, # 分
            # hours=8,   # 小时
            # weeks=2,   # 周
        )

        # # 创建或更新CrontabSchedule
        # schedule, _ = DjangoCeleryBeatCrontabschedule.objects.get_or_create(
        #     minute=cron_list[0],
        #     hour=cron_list[1],
        #     day_of_week=cron_list[2],
        #     day_of_month=cron_list[3],
        #     month_of_year=cron_list[4],
        # )

        # 创建或更新CrontabSchedule
        schedule, _ = DjangoCeleryBeatClockedschedule.objects.get_or_create(
            clocked_time=task_time
        )

        if DjangoCeleryBeatPeriodictask.objects.filter(name=task_name).exists():
            return Response(
                {
                    "data": [],
                    "status": status.HTTP_400_BAD_REQUEST,
                    "message": "task name already exists",
                }
            )

        # periodic_task = DjangoCeleryBeatPeriodictask.objects.create(
        #     crontab=schedule,
        #     name=task_name,
        #     task="mysqldb.tasks.run_test_task",
        # )
        # periodic_task.enabled = True
        # periodic_task.save()

        # 创建任务
        # DjangoCeleryBeatPeriodictask(
        #     name=task_name,
        #     task="mysqldb.tasks.run_test_task",
        #     args=None,
        #     kwargs=None,
        #     enable=1,
        #     total_run_count=1,
        #     date_changed=timezone.now(),
        #     description="描述",
        #     one_off=1,
        #     headers="",
        #     clocked_id=schedule.id,
        # ).save()

        return Response({"status": status.HTTP_200_OK, "message": "success"})

        # -----------------------------------------------------
        logger.info(f"[mysqldb] [TEST] 收到post消息")
        return Response({"rescode": 200, "resmsg": ""})


# ===========================================================
class taskSyncfromIDViewSet(viewsets.ModelViewSet):
    __title__ = "查询异步任务的执行结果"
    __group__ = "公用接口"
    __info__ = {
        "get": "查询异步任务的执行结果",
        "post": "查询异步任务的执行结果",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>查询异步任务的执行结果</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = taskSyncfromIDSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()

        # 查询缓存数据
        rds = get_redis_connection("celeryReses")
        if not rds.exists(f'celery-task-meta-{serializer.data.get("event")}'):
            return Response({"rescode": 400, "resmsg": "未找到数据"})
        return Response(
            {
                "rescode": 200,
                "resmsg": rds.get(f'celery-task-meta-{serializer.data.get("event")}'),
            }
        )


# ===========================================================
class WeChatSelfMenuListViewSet(viewsets.ModelViewSet):
    __title__ = "查询公众号菜单接口"
    __group__ = "公用接口"
    __info__ = {"post": "查询公众号菜单接口"}
    __doc__ = """
    create:
    <h4>查询公众号菜单接口</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        WX = wxChatRequest()
        r = WX.hasMenuList()
        return Response({"rescode": 200, "resmsg": r})


class WeChatSelfMenuSetViewSet(viewsets.ModelViewSet):
    __title__ = "设置公众号菜单接口"
    __group__ = "公用接口"
    __info__ = {"post": "设置公众号菜单接口"}
    __doc__ = """
    create:
    <h4>设置公众号菜单接口</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = WeChatSelfMenuSetSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.data.get("data")
        WX = wxChatRequest()
        r = WX.setMenuList(data)
        return Response({"rescode": 200, "resmsg": r})


# =============================================================
class wxRequestLoginCodeViewSet(viewsets.ModelViewSet):
    __title__ = "公众号登录授权"
    __group__ = "公用接口"
    __info__ = {"post": "公众号登录授权"}
    __doc__ = """
    create:
    <h4>公众号登录授权</h4>
        `注意编码转换`
        返回地址字符串，需要将该地址生成二维码供用户扫描。
        用户扫描授权登录后,本地用户Token保存缓存180秒。
        需要前端页面轮询以下接口 #11。
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        SDK = wxChatRequest()

        code = has_chocode(6)
        params = {
            "appid": SDK.CONF.chat_appid,  # wxConf["appid"],
            "redirect_uri": SDK.notify,  # wxConf["rect"],  # http://ppt.3vppt.com/api/wxRect
            "response_type": "code",
            "scope": SDK.scope,  # wxConf["scope"],
            "state": code,
            "connect_redirect": 1,
        }
        url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
        url += urlencode(params)
        url += "#wechat_redirect"
        return Response({"rescode": 200, "resmsg": url})


class wxRequestLoginCodeV2ViewSet(viewsets.ModelViewSet):
    __title__ = "公众号扫码登录授权"
    __group__ = "公用接口"
    __info__ = {"post": "公众号扫码登录授权"}
    __doc__ = """
    create:
    <h4>公众号扫码登录授权</h4>
        获取登录二维码和state
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        # 1000场景值
        code = has_chocode(6)
        WX = wxChatRequest()
        token = WX.hasToken()
        # print("我的token :", token)
        if not token or token.get("errcode"):
            return Response({"rescode": 400, "resmsg": "获取token失败"})
        url = WX.hasQrCode(token["access_token"], code)
        # print("我的url",url)
        logger.info(f"[扫码登录] 请求地址 {url}")
        if not url:
            return Response({"rescode": 400, "resmsg": "获取token失败"})
        return Response({"rescode": 200, "resmsg": url["url"], "code": code})


class wxRequestLoginTokenViewSet(viewsets.ModelViewSet):
    __title__ = "查询扫码登录本地Token"
    __group__ = "公用接口"
    __info__ = {"post": "查询扫码登录本地Token"}
    __doc__ = """
    create:
    <h4>查询扫码登录本地Token</h4>
    返回： {token}
    请求头: headers = {Authorization: token}    
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = wxRequestLoginTokenSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 查询缓存数据
        rds = get_redis_connection("sysconf")
        if not rds.exists(serializer.data.get("state")):
            return Response({"rescode": 400, "resmsg": "位置未找到数据"})
        return Response(
            {"rescode": 200, "resmsg": rds.get(serializer.data.get("state"))}
        )


class wxChangeLoginTokenViewSet(viewsets.ModelViewSet):
    __title__ = "交换本地Token"
    __group__ = "公用接口"
    __info__ = {"post": "交换本地Token"}
    __doc__ = """
    create:
    <h4>交换本地Token</h4>
        `微信登录, 提供H5页面和小程序使用`
    返回： {token}
    请求头: headers = {Authorization: token}    
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = wxChangeLoginTokenSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 查询用户
        try:
            openid = serializer.data.get("openid")
            wx = AllinpayWxchatList.objects.get(Q(openid=openid) | Q(appid=openid))
            ur = AllinpayUserUserList.objects.get(id=wx.userid)
        except BaseException as err:
            return Response({"rescode": 400, "resmsg": "openid 无效"})
        else:
            token = get_tokens_for_user(ur)["access"]
            return Response(
                {
                    "rescode": 200,
                    "resmsg": f"Bearer {token}",
                    "userid": ur.id,
                    "openid": wx.openid,
                    "appid": wx.appid,
                }
            )


class wxAppChangeLoginTokenViewSet(viewsets.ModelViewSet):
    __title__ = "小程序本地Token"
    __group__ = "公用接口"
    __info__ = {"post": "交换本地Token"}
    __doc__ = """
    create:
    <h4>交换本地Token</h4>
        `小程序直接登录`
    返回： {token}
    请求头: headers = {Authorization: token}    
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = wxChangeLoginTokenSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 查询用户
        try:
            wx = AllinpayWxchatList.objects.get(openid=serializer.data.get("appid"))
            ur = AllinpayUserUserList.objects.get(id=wx.userid)
        except BaseException as err:
            return Response({"rescode": 400, "resmsg": "openid 无效"})
        else:
            token = get_tokens_for_user(ur)["access"]
            return Response(
                {
                    "rescode": 200,
                    "resmsg": f"Bearer {token}",
                    "userid": ur.id,
                    "openid": wx.appid,
                }
            )


class wxappLoginViewSet(viewsets.ModelViewSet):
    __title__ = "小程序登录"
    __group__ = "公用接口"
    __info__ = {"post": "小程序登录"}
    __doc__ = """
    create:
    <h4>小程序登录</h4>
        `小程序登录`
        异步接口
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = wxappLoginSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        r = wxAppLogin.delay(**serializer.data)
        return Response({"rescode": 200, "resmsg": r.task_id})


# =============================================================


class HelloWorld(viewsets.ModelViewSet):
    __title__ = "测试接口"
    __group__ = "管理员模板"
    __info__ = {
        "get": "测试接口",
        "post": "测试接口",
        "patch": "编辑",
        "delete": "移除",
    }
    __doc__ = """	list:
    <h4>列表</h4>
    retrieve:
    <h4>详情</h4>
    create:
    <h4>注册员工</h4>
        ?version=1
    partial_update:
    <h4>编辑</h4>
    delete:
    <h4>移除</h4>"""
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    versioning_class = MyDefaultVersioning
    serializer_class = NoneSerializer
    queryset = None

    # filter_backends = [ListDjangoFilterBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ["status"]
    # search_fields = ['phone','email']

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return NoneSerializer

    def list(self, request, *args, **kwargs):
        # queryset = self.filter_queryset(self.get_queryset())
        # c = queryset.count()
        # page = self.paginate_queryset(queryset)
        # serializer = self.get_serializer(page, many=True)
        # return Response(
        #     {
        #         "rescode": 200,
        #         "resmsg": serializer.data,
        #         "count": c,
        #         "size": self.pagination_class.page_size,
        #     }
        # )
        return Response({"rescode": 200, "resmsg": "HelloWorld"})

    def retrieve(self, request, *args, **kwargs):
        # instance = self.get_object()
        # serializer = self.get_serializer(instance)
        # return Response({"rescode": 200, "resmsg": serializer.data})
        return Response({"rescode": 200, "resmsg": "HelloWorld"})


# -------------------------------------------------------------------


class AllinpayWxchatListViewSet(viewsets.ModelViewSet):
    __title__ = "微信个人信息"
    __group__ = "公用接口"
    __info__ = {"get": "查询微信个人信息", "put": "编辑微信个人信息"}
    __doc__ = """	
    list:
    <h4>LOL微信个人信息列表</h4>
        ?search=<openid> 返回数组
    retrieve:
    <h4>LOL微信个人信息详情</h4>
        /<id>/ 返回对象
    create:
    <h4>创建微信个人信息</h4>
    update:
    <h4>编辑微信个人信息</h4>
    partial_update:
    <h4>编辑微信个人信息</h4>     
    delete:
    <h4>移除微信个人信息</h4>"""
    http_method_names = ["get", "patch"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = WeChatUserinfoSerializer
    queryset = AllinpayWxchatList.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ['status']
    search_fields = ["openid", "unionid"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return WeChatUserinfoSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayWxchatInfoViewSet(viewsets.ModelViewSet):
    __title__ = "微信个人信息(自己)"
    __group__ = "公用接口"
    __info__ = {"post": "查询微信个人信息(自己)"}
    __doc__ = """	
    list:
    <h4>LOL微信个人信息列表</h4>
        ?search=<openid> 返回数组
    retrieve:
    <h4>LOL微信个人信息详情</h4>
        /<id>/ 返回对象
    create:
    <h4>查询微信个人信息(自己)</h4>
    update:
    <h4>编辑微信个人信息</h4>
    partial_update:
    <h4>编辑微信个人信息</h4>     
    delete:
    <h4>移除微信个人信息</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = AllinpayWxchatList.objects.all()

    def create(self, request, *args, **kwargs):
        uid = request.user.id if request.user else 1
        try:
            r = self.get_queryset().get(userid=uid)
        except BaseException as err:
            return Response({"rescode": 404, "resmsg": "未找到该用户信息"})
        return Response({"rescode": 200, "resmsg": WeChatUserinfoSerializer(r).data})


class wxConnectActPostViewSet(viewsets.ModelViewSet):
    __title__ = "提交远程任务"
    __group__ = "公用接口"
    __info__ = {
        "get": "查询远程任务",
        "post": "提交远程任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>查询远程任务</h4>
        录屏工具的远程操作指令
    retrieve:
    <h4>查询远程任务</h4>
        `禁用`
    create:
    <h4>提交远程任务</h4>
        录屏工具的远程操作指令
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = wxConnectActSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()

        uid = request.user.id if request.user else 1
        rds = get_redis_connection("sysconf")
        rds.rpush(f"act_{uid}", serializer.data.get("act"))
        rds.expire(f"act_{uid}", 180)

        return Response({"rescode": 200, "resmsg": serializer.data})


class wxConnectActListViewSet(viewsets.ModelViewSet):
    __title__ = "调取远程任务"
    __group__ = "公用接口"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "调取远程任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>调取远程任务</h4>
        录屏工具的远程操作指令
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [MyPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        uid = request.user.id if request.user else 1
        rds = get_redis_connection("sysconf")
        res = rds.blpop(f"act_{uid}", 1)
        return Response({"rescode": 200, "resmsg": res})


class AllinpayDeviceLicenseViewSet(viewsets.ModelViewSet):
    __title__ = "离线项目授权"
    __group__ = "离线项目"
    __info__ = {
        "get": "查询离线项目授权列表",
        "post": "创建离线项目授权",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>离线项目授权列表</h4>
    retrieve:
    <h4>离线项目授权详情</h4>
    create:
    <h4>创建离线项目授权</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayDeviceLicenseSerializer
    queryset = AllinpayDeviceLicense.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ['status']
    search_fields = ["serialid", "name", "cipher", "over"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayDeviceLicenseSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        uid = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=uid, creattime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})


# ============================================================
# Celery
# ============================================================
class DjangoCeleryBeatClockedscheduleViewSet(viewsets.ModelViewSet):
    __title__ = "固定时间"
    __group__ = "计划任务"
    __info__ = {
        "get": "查询固定时间列表",
        "post": "创建固定时间",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>固定时间列表</h4>
    retrieve:
    <h4>固定时间详情</h4>
    create:
    <h4>创建固定时间</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = ModelDjangoCeleryBeatClockedscheduleSerializer
    queryset = ClockedSchedule.objects.all()

    # filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ['status']
    # search_fields = ['phone','email']

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return ModelDjangoCeleryBeatClockedscheduleSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class DjangoCeleryBeatCrontabscheduleViewSet(viewsets.ModelViewSet):
    __title__ = "Cron时间格式"
    __group__ = "计划任务"
    __info__ = {
        "get": "查询Cron时间格式列表",
        "post": "创建Cron时间格式",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>Cron时间格式列表</h4>
    retrieve:
    <h4>Cron时间格式详情</h4>
    create:
    <h4>创建Cron时间格式</h4>
        minute = "*" # 每分钟命中
        minute = "*/6" # 每6分钟命中
        minute = "5" # 5分整命中
        minute = "2,16,32" # 2,16,32分整命中       
        其他字段相同,要求至少1个数字参数,时区默认+8区
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = DjangoCeleryBeatCrontabscheduleSerializer
    queryset = CrontabSchedule.objects.all()

    # filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ['status']
    # search_fields = ['phone','email']

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return DjangoCeleryBeatCrontabscheduleSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class DjangoCeleryBeatIntervalscheduleViewSet(viewsets.ModelViewSet):
    __title__ = "频率间隔"
    __group__ = "计划任务"
    __info__ = {
        "get": "查询频率间隔列表",
        "post": "创建频率间隔",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>频率间隔列表</h4>
    retrieve:
    <h4>频率间隔详情</h4>
    create:
    <h4>创建频率间隔</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = DjangoCeleryBeatIntervalscheduleSerializer
    queryset = IntervalSchedule.objects.all()

    # filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ['status']
    # search_fields = ['phone','email']

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return DjangoCeleryBeatIntervalscheduleSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class DjangoCeleryBeatPeriodictaskViewSet(viewsets.ModelViewSet):
    __title__ = "计划任务列表"
    __group__ = "计划任务"
    __info__ = {
        "get": "查询计划任务列表",
        "post": "启 or 停计划任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除计划任务",
    }
    __doc__ = """	
    list:
    <h4>计划任务列表</h4>
    retrieve:
    <h4>启 or 停计划任务</h4>
    create:
    <h4>启 or 停计划任务</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除计划任务</h4>"""
    http_method_names = ["get", "delete"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = DjangoCeleryBeatPeriodictaskSerializer
    queryset = PeriodicTask.objects.filter(task="rebot.tasks.AI_Auto_Tasks_Event")

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    filterset_class = PeriodicTaskFilterSet
    # filterset_fields = ["crontab", "interval", "clocked"]
    # search_fields = ['phone','email']

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return DjangoCeleryBeatPeriodictaskSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.enabled = False if instance.enabled else True
        instance.save()
        # PeriodicTasks.update_changed()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        PeriodicTasks.update_changed()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        PeriodicTasks.update_changed()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


# 检查视图
filter_views(globals())
